<template>
  <div class="content">
    <div class="bg">
      <div class="title-box">
        <div class="title-name">AI智能识别交互</div>
      </div>
      <div class="content-box center">
        <div class="chat-box">
          <scrollview :scroll-y="true" style="height: 60vh;" ref="scrollview">
            <div v-for="(item,index) in chatLIst" :key="index" style="padding: 2vh 0vw;">
              <div class="left">
                <div @click="playerMp3(item.questionVoiceUrl)">
                  <img src="../../../static/image/question.png" mode="aspectFit" style="width: 20vw;">
                </div>
                <div class="left-text" v-if="item.questionTxtContent">
                  {{item.questionTxtContent}}
                </div>
              </div>
              <div class="right" v-if="item.showAnser">
                <div @click="playerMp3(item.answerVoiceUrl)" v-if="item.answerVoiceUrl">
                  <img src="../../../static/image/answer.png" alt="" mode="aspectFit" style="width: 20vw;">
                </div>
                <div class="right-text" v-if="item.answerTxtContent">
                  {{item.answerTxtContent}}
                </div>
              </div>
              <div class="right" v-else>
                <img src="../../../static/image/aithink.png" alt="" mode="aspectFit" style="width: 12vw;">
              </div>
            </div>
          </scrollview>
        </div>
      </div>
      <!-- <div class="voice-box center" style="">
        <div @mousedown="start" @mouseup="end">
          <img v-if="isTouch" src="../../../static/image/voice-touch.png" mode="aspectFit" style="width: 5vw;" />
          <img v-else src="../../../static/image/voice.png" mode="aspectFit" style="width: 5vw;" />
        </div>
        <div class="tips">{{tips}}</div>
      </div> -->
      <div class="voice-box center">
        <button v-if="isTouch" @click="end" class="end"></button>
        <button v-else @click="start" class="start"></button>
      </div>
    </div>
  </div>
</template>

<script>
  import scrollview from "@/components/scrollview.vue"
  import {
    uploadAi
  } from "@/api/interact/index.js"
  export default {
    data() {
      return {
        tips: "请长按说话",
        chatLIst: [],
        isTouch: false,
        mp3Url: "http://139.224.71.79:8096/profile/upload/answer1/2.MP3",
        questUrl: "http://139.224.71.79:8096/profile/upload/2023/09/23/1695483656110_20230923234058A031.mp3",
        audio: new Audio(),
        /**鼠标点击的开始时间*/
        mouseDownTime: 0,
        dot: "", //记录settimeout
        params: ""
      }
    },
    created() {
      // this.init()
    },
    components: {
      scrollview
    },
    watch: {
      isTouch(newVal) {
        let that = this;
        clearTimeout(that.dot)
        if (newVal) {
          //超过30秒,结束录音
          that.dot = setTimeout(() => {
            //调用第三个接口
            console.log("自动结束")
            that.end()
          }, 1000 * 30)
        }
      }
    },
    methods: {
      init: function() {
        for (let i = 0; i < 15; i++) {
          let obj = {}
          obj["questionVoiceUrl"] = this.questUrl;
          obj["answerVoiceUrl"] = this.mp3Url;
          this.chatLIst.push(obj)
        }
        // this.chatLIst=[{"questionVoiceUrl":this.questUrl,"answerVoiceUrl":this.mp3Url}]
      },
      start: function(e) {
        //记录按下的时间
        this.mouseDownTime = new Date().getTime();
        this.isTouch = true
        this.RealizeRecorder.startRecord()
      },
      end: function(e) {
        //少于1.5秒不触发下面功能
        let that = this;
        clearTimeout(that.dot)
        let curentTime = new Date().getTime();
        if (curentTime - this.mouseDownTime < 1000) {
          this.isTouch = false
          alert("不能小于1秒哦~")
          return
        }
        this.isTouch = false
        this.RealizeRecorder.pauseRecord();
        const wavBlob = this.RealizeRecorder.recorder.getWAVBlob();
        // 创建一个formData对象
        var formData = new FormData()
        let fileName = new Date().getTime() + ".mp3";
        const newbolb = new Blob([wavBlob], {
          type: 'audio/mp3'
        })
        // 获取当时时间戳作为文件名
        const fileOfBlob = new File([newbolb], fileName)
        formData.append('file', fileOfBlob)
        formData.append('fileName', fileName)
        that.params = that.chatLIst.length + 1
        formData.append('params', that.params)

        that.setVirtuallyChat(that.params);

        uploadAi(formData).then(res => {
          if (res.code == 0) {
            //定义一个变量,操作是否展播放和展示声音和答案
            res["showAnser"] = false;
            //获取随机数,更真实(1~2秒)
            let randomNum = Math.round(Math.random() * 1 + 1);

            let index = this.chatLIst.findIndex((item => {
              return item.params == Number(res.params)
            }))
            //有值返回
            if (index > -1) {
              // console.log(index)
              let currentObj = that.chatLIst[index]
              // console.log(currentObj)
              currentObj.answerTxtContent = res.answerTxtContent
              currentObj.answerVoiceUrl = res.answerVoiceUrl
              currentObj.questionTxtContent = res.questionTxtContent
              currentObj.questionVoiceUrl = res.questionVoiceUrl
              currentObj["showAnser"] = true
              that.chatLIst.splice(index, 1, currentObj)
              // console.log(that.chatLIst)
            }

            this.$nextTick(() => {
              that.autoToBottom()
            });
            clearTimeout(that.dot)
            if (res.answerVoiceUrl) {
              that.dot = setTimeout(() => {
                res["showAnser"] = true
                that.playerMp3(res.answerVoiceUrl)
                that.$nextTick(() => {
                  that.autoToBottom()
                });
              }, randomNum * 1000)
            }
          }
        })
      },
      playerMp3: function(url) {
        if (!url) {
          return
        }
        this.audio.src = url;
        this.audio.play();
      },
      /**
       * 虚拟对话
       */
      setVirtuallyChat: function(params) {
        let that = this
        let obj = {}
        obj["params"] = params;
        obj["questionVoiceUrl"] = ""
        obj["answerVoiceUrl"] = ""
        obj["answerTxtContent"] = "思考中..."
        obj["showAnser"] = false
        this.chatLIst.push(obj)
        that.$nextTick(() => {
          that.autoToBottom()
        });
        console.log(this.chatLIst)
      },
      autoToBottom: function() {
        this.$refs.scrollview.autoToBottom()
      }
    },
    beforeDestroy() {
      //释放
      clearTimeout(this.dot)
      this.audio.pause();
    }

  }
</script>

<style scoped>
  .content {
    height: 100%;
    width: 100%;
  }

  .bg {
    background-size: 100% 100%;
    height: 100%;
    width: 100%;
    background-image: url('../../../static/image/background.jpg');
    background-position: center;
    background-repeat: no-repeat;
  }

  .title-box {
    position: relative;
    text-align: center;
    top: 8vh;
    color: #fff;
    font-size: 20px;

  }

  .chat-box {
    height: 60vh;
    width: 45vw;
    color: #fff;
  }

  .voice-box {
    position: relative;
    /* display: flex; */
    /* justify-content: center; */
    bottom: -8vh;
    text-align: center;
  }

  .voice-notouch {
    background-image: url("../../../static/image/voice.png");
    width: 5vw;
    height: 5vh;
    position: relative;
  }

  .voice-touch {
    background-image: url("../../../static/image/voice-touch.png");
    width: 5vw;
    height: 5vh;
    position: relative;
  }

  .content-box {
    display: flex;
    align-items: center;
    height: 70vh;
    width: 70vw;
    justify-content: space-around;
    position: relative;
    top: 10vh;
  }

  .center {
    left: 0;
    right: 0;
    margin: auto;
  }

  .left {
    text-align: left;
  }

  .right {
    text-align: right;
  }

  .left-text {
    width: 25vw;
    padding-left: 3vw;
    font-size: 16px;
  }

  .right-text {
    padding-left: 18vw;
    width: 100%;
    padding-right: 4vw;
    font-size: 16px;
  }

  .tips {
    padding-top: 1vh;
    color: #fff;
  }

  .start {
    background-image: url("../../../static/image/voice.png");
    width: 80px;
    height: 80px;
    background-position: center;
    background-repeat: no-repeat;
    border-radius: 50%;
    background-size: 100% 100%;
    border: none;
  }

  .end {
    background-image: url("../../../static/image/voice-touch.png");
    width: 80px;
    height: 80px;
    background-position: center;
    background-repeat: no-repeat;
    border-radius: 50%;
    background-size: 100% 100%;
    border: none;
  }
</style>